package xin.marcher.module.construction.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Repository;
import xin.marcher.module.common.exception.CommonErrorCodeEnum;
import xin.marcher.module.common.exception.ProductBizException;
import xin.marcher.module.construction.converter.BrandConverter;
import xin.marcher.module.construction.domain.dto.BrandInfoDTO;
import xin.marcher.module.construction.domain.dto.BrandListDTO;
import xin.marcher.module.construction.domain.entity.BrandInfoDO;
import xin.marcher.module.construction.domain.request.BrandRequest;
import xin.marcher.module.construction.domain.request.QueryBrandRequest;
import xin.marcher.module.construction.mapper.BrandInfoMapper;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 商品审核 资源管理
 */
@Repository
public class BrandRepository {

    @Resource
    private BrandConverter brandConverter;

    @Resource
    private BrandInfoMapper brandInfoMapper;

    /**
     * @param brandRequest
     * @return
     */
    public void saveOrUpdate(BrandRequest brandRequest) {

        if (Objects.isNull(brandRequest.getId())) {
            this.save(brandRequest);
        } else {
            this.update(brandRequest);
        }

    }

    /**
     * @param brandRequest
     * @return
     */
    public void save(BrandRequest brandRequest) {
        BrandInfoDO brandInfoDO = brandConverter.converterDO(brandRequest);
        brandInfoDO.initCommon();

        int count = brandInfoMapper.insert(brandInfoDO);
        if (count <= 0) {
            throw new ProductBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * @param brandRequest
     * @return
     */
    public void update(BrandRequest brandRequest) {
        brandInfoMapper.updateById(brandConverter.converterDO(brandRequest));
    }


    public BrandListDTO getBrandInfoByLike(QueryBrandRequest queryBrandRequest) {
        LambdaQueryWrapper<BrandInfoDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(BrandInfoDO::getBrandName, queryBrandRequest.getBrandNameLike());
        List<BrandInfoDO> brandInfoDOS = brandInfoMapper.selectList(queryWrapper);

        List<BrandInfoDTO> brandInfoDTOList = brandConverter.converterDTOList(brandInfoDOS);
        return new BrandListDTO(brandInfoDTOList);
    }
}
